/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.antColonyOptimisation.ant.parser;

import org.utc.ia04.antsontheweb.knowledgeBase.KnowledgeBaseAgent;
import org.utc.ia04.antsontheweb.pheromone.PheromoneManagerAgent;
import org.utc.ia04.antsontheweb.utilities.PheromoneManagerMessage;
import org.utc.ia04.antsontheweb.utilities.Requete;
import org.utc.ia04.antsontheweb.utilities.RequeteException;

import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

public class AntParserBhv extends CyclicBehaviour
{
	//serialVersionUID
	private static final long serialVersionUID = -3664020655128335701L;
	
	public void action() 
	{
		ACLMessage receivedMsg = myAgent.receive();
		if( receivedMsg == null) block();
		else
		{
			// on parse pour savoir si on a afaire � une fourmis morte ou � des ressource collectees
			String msgContent =  receivedMsg.getContent();
			try
			{
				Requete query = Requete.deserialize_withException(msgContent, myAgent, receivedMsg);
				switch(query.getType())
				{
				case Requete.KB_ANSWER:
					boolean kbAnswer = Boolean.parseBoolean(query.getContent());
					if (kbAnswer)
					{
						ACLMessage ressourceMsg = new ACLMessage(ACLMessage.INFORM);
						Requete pickupQuery = new Requete(Requete.ANTPARSER_RESSOURCEPICKUP,"RESSOURCE_PICKUP");
						ressourceMsg.setContent(pickupQuery.serialize());
						ressourceMsg.addReceiver(((AntParserAgent)myAgent).getAntAID());
						myAgent.send(ressourceMsg);
					}
					else 
					{
						ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
						PheromoneManagerMessage phMsg = new PheromoneManagerMessage(((AntParserAgent)myAgent).getLinks());
						Requete linkQuery = new Requete(Requete.ANTPARSER_ASKFORPHEROMONE,phMsg.serialize());
						msg.setContent(linkQuery.serialize());
						DFAgentDescription template = new DFAgentDescription();
						ServiceDescription sd = new ServiceDescription();
						sd.setType(PheromoneManagerAgent.dfType); 
						template.addServices(sd);
						try
						{
							DFAgentDescription[] result = DFService.search(myAgent, template);
							int nbAgent = result.length; int selection = (int) (Math.random()*nbAgent);
							if(nbAgent > 0) msg.addReceiver(result[selection].getName());
						}
						catch(Exception fe)
						{
							System.out.println(fe.getMessage());
						}
						msg.addReplyTo(((AntParserAgent)myAgent).getPathFinderAID());
						myAgent.send(msg);
						
						//envoi message pour incrementer ticker Time de Ant
						ACLMessage incTickMsg = new ACLMessage(ACLMessage.REQUEST);
						incTickMsg.addReceiver(((AntParserAgent)myAgent).getAntAID());
						Requete incTickReq = new Requete(Requete.INC_TICK, null);
						incTickMsg.setContent(incTickReq.serialize());
						myAgent.send(incTickMsg);
					}
					break;
				case Requete.KB_ERROR:
					ACLMessage backtrackMsg = new ACLMessage(ACLMessage.REQUEST);
					Requete linkQuery = new Requete(Requete.ANTPARSER_DOBACKTRACK,null);
					backtrackMsg.setContent(linkQuery.serialize());
					
					backtrackMsg.addReceiver(((AntParserAgent)myAgent).getPathFinderAID());
					myAgent.send(backtrackMsg);
					//DEBUG
					System.out.println("KB_ERROR");
					
					//envoi message pour incrementer ticker Time de Ant
					ACLMessage incTickMsg = new ACLMessage(ACLMessage.REQUEST);
					incTickMsg.addReceiver(((AntParserAgent)myAgent).getAntAID());
					Requete incTickReq = new Requete(Requete.INC_TICK, null);
					incTickMsg.setContent(incTickReq.serialize());
					myAgent.send(incTickMsg);
					break;
				case Requete.HTTPREQ_TO_PARSER:
					ACLMessage tickMsg = myAgent.blockingReceive();
					try
					{
						Requete tickQuery = Requete.deserialize_withException(tickMsg.getContent(), myAgent, receivedMsg);
						switch(tickQuery.getType())
						{
						case Requete.ANT_GO:
							ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
							Requete webTypeQuery = new Requete(Requete.KB_GIVE_WEBSITE_TYPE,((AntParserAgent)myAgent).sortHtmlContent(msgContent).serialize());
							((AntParserAgent)myAgent).setLinks(msgContent);
							msg.setContent(webTypeQuery.serialize());
							DFAgentDescription template = new DFAgentDescription();
							ServiceDescription sd = new ServiceDescription();
							sd.setType(KnowledgeBaseAgent.dfType); 
							template.addServices(sd);
							try
							{
								DFAgentDescription[] result = DFService.search(myAgent, template);
								int nbAgent = result.length; int selection = (int) (Math.random()*nbAgent);
								if(nbAgent > 0) msg.addReceiver(result[selection].getName());
							}
							catch(Exception fe) {System.out.println(fe.getMessage());}
							myAgent.send(msg);
							break;
						case Requete.ANT_DYING:
							((AntParserAgent)myAgent).setMyAntIsDead();
							myAgent.doDelete();
							block();
							break;
						default:
							//System.out.println("BIGDEBUG: "+myAgent.getName()+ tickMsg);
							throw new SecurityException("Message:"+tickMsg.getContent()+" was received and ignored.");
						}
					}
					catch(RequeteException e){System.out.println(e.toString());}
				case Requete.ANT_GO:
					break;
				case Requete.ANT_DYING:
					myAgent.doDelete();
					block();
					break;
				default:
					System.out.println("PARSER BHV : " + myAgent.getLocalName() +" received message from " + receivedMsg.getSender().getLocalName() + msgContent + " and not know how to treat it.");
					break;
				}
			}
			catch(RequeteException e) { }
		}

		
	}
}